<?php
/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Model', 'Model');
App::uses('Security', 'Utility');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class AppModel extends Model {
    
    // define delete method
    var $useSoftDelete = true;
    
    // define universal date format
    var $dateFormat = 'Y-m-d H:i:s';
    
    public function beforeSave() {
        
        $continue = true;
        
        if (!isset($this->id)) {
            $this->data[$this->alias]['created'] = date($this->dateFormat);
        }
        
        return $continue;
    }
    
    public function delete($id = null, $cascade = true) {
        if ($this->useSoftDelete) {
            return $this->updateAll(array('deletedOn' => "'" . date($this->dateFormat) . "'"),array('id' => $id));
        } else {
            return parent::delete($id,$cascade);
        } 
    }
    
    public function deleteAll($conditions, $cascade = true, $callbacks = false) {       
        if ($this->useSoftDelete) {
            return $this->updateAll(array('deletedOn' => "'" . date($this->dateFormat . "'")),$conditions);
        } else {
            return parent::deleteAll($conditions,$cascade,$callbacks);
        }    
    }
    
    public function getActiveRecords() {
        return $this->find('all',array('conditions' => array('deletedOn' => null)));
    }
    
    public function activeRecordExists($id) {
        return ($this->find('first',array('conditions' => array('id' => $id, 'deletedOn' => null))) != null);
    }
    
    public function recordExists($id) {
        return ($this->find('first',array('conditions' => array('id' => $id))) != null);
    }
    
    public function getActiveRecord($id) {
        return $this->find('first',array('conditions' => array('id' => $id,'deletedOn' => null)));
    }
    
    public function getRecord($id) {
        return $this->find('first',array('conditions' => array('id' => $id)));
    }
    
    public function sanitizeAll() {
        return true;
    }
    
    public function clearTable() {
        $this->query("TRUNCATE table {$this->table};");
    }
    
}
